package vn.hanelsoft.openwifi.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import vn.hanelsoft.openwifi.R;
import vn.hanelsoft.openwifi.common.ConstCommon;
import vn.hanelsoft.openwifi.common.UtilsCommon;
import vn.hanelsoft.openwifi.common.network_service.utils.NetworkUtil;
import vn.hanelsoft.openwifi.model.adapter.AdapterWifi;
import vn.hanelsoft.openwifi.model.adapter.AdapterWifiSave;
import vn.hanelsoft.openwifi.model.delegate.ServerDelegate;
import vn.hanelsoft.openwifi.model.entity.EntityWifi;
import vn.hanelsoft.openwifi.model.object.ObjectWifi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class FreeWifiActivity extends Activity implements OnClickListener {

	Context mContext;
	ArrayList<ObjectWifi> listWifi;
	AdapterWifi adapter;
	AdapterWifiSave adapterWifiSave;

	ViewFlipper vf;
	ListView listView, listViewSave;
	ProgressBar progressBarLoading;
	ObjectWifi mObjectWifi;
	public static boolean checkDisconnectWifi = true;
	EntityWifi mEntityWifi;

	ArrayList<ObjectWifi> listWifiOnServer, listWifiSave;
	private AdView mAdView;

	// Current Location
	private LocationManager locManager;
	private LocationListener locListener;
	private Location currentLocation;
	private boolean gps_enabled = false;
	private boolean network_enabled = false;

	int timeout = 30;
	boolean isClickAds;
	
	private TextView mTextDown;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_free_wifi);
		addViewAds();
		initDB();
		initView();
		ServerDelegate.getWifi(mhandler, "", "");
		
		mThread.start();
		
		mTextDown.setTypeface(UtilsCommon.getFontCustom(this));
	}

	Thread mThread = new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setTextDown();
					}
				});
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	});

	void setTextDown() {
		String strMinuter = "";
		String strSecond = "";
		String strTime = "";
		if (ConstCommon.isServiceRunning) {
			if (ConstCommon.minuterService > 9)
				strMinuter += ConstCommon.minuterService;
			else
				strMinuter += "0" + ConstCommon.minuterService;
			if (ConstCommon.secondService> 9)
				strSecond += ConstCommon.secondService;
			else
				strSecond += "0" + ConstCommon.secondService;
			strTime = strMinuter + ":" + strSecond;
		}
		
		mTextDown.setText(strTime);
	}

	void loadWifiFromServer() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (currentLocation == null) {
					try {
						Thread.sleep(2000);
						timeout--;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (currentLocation != null) {
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								ServerDelegate.getWifi(mhandler,
										String.valueOf(currentLocation
												.getLatitude()), String
												.valueOf(currentLocation
														.getLongitude()));
							}
						});
					}

				}
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.free_wifi_go:
			if (NetworkUtil.checkNetWork(getApplicationContext())) {
				checkDisconnectWifi = false;
				Intent intent = new Intent(mContext,
						ChromeBrowserActivity.class);
				intent.putExtra(ConstCommon.KEY_LINK_POLICY,
						getString(R.string.link_policy));
				((Activity) mContext).startActivity(intent);
				overridePendingTransition(
						R.drawable.activity_transaction_trans_left_in,
						R.drawable.activity_transaction_trans_left_out);
			} else {
				Toast.makeText(this, getString(R.string.not_connect_internet),
						Toast.LENGTH_LONG).show();
			}
			break;

		default:
			break;
		}
	}

	@Override
	protected void onStop() {
		if (checkDisconnectWifi == false) {
			checkDisconnectWifi = true;
		} else if (isClickAds) {
			isClickAds = false;
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService = (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterWait;
				ConstCommon.secondService = 0;
				ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE), String
						.valueOf(ConstCommon.totalSecondService));
			}
		} else {
			//
			if (ConstCommon.isServiceRunning) {
				if (ConstCommon.isFirst){
					ConstCommon.totalSecondService = (ConstCommon.minuterFirst * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
					ConstCommon.isFirst = false;
				}
				else
					ConstCommon.totalSecondService += (ConstCommon.minuterWait * 60 - (ConstCommon.minuterService * 60 + ConstCommon.secondService));
				ConstCommon.minuterService = ConstCommon.minuterFirst;
				ConstCommon.secondService = 0;
			}
			ServerDelegate.updateTotalTimeShowAd(mhandler1, UtilsCommon
					.getStringSetting(getBaseContext(),
							ConstCommon.KEY_WIFI_STORE), String
					.valueOf(ConstCommon.totalSecondService));
			ConstCommon.totalSecondService = 0;
			ConstCommon.isServiceRunning = false;
			UtilsCommon.setStringSetting(getBaseContext(), ConstCommon.KEY_WIFI_STORE, "");
			Log.i("Service1", "Kill");
		}
		super.onStop();
//		if (checkDisconnectWifi == false) {
//			checkDisconnectWifi = true;
//		} else {
//			UtilsCommon.disConnectWifi(this);
//		}
//		super.onStop();
	}


	Handler mhandler1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				UtilsCommon.killApp(getApplicationContext());
			}
		}
	};

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		checkDisconnectWifi = false;
		activityFinish();
	}

	@Override
	protected void onPause() {
		mAdView.pause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdView.resume();
	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onDestroy() {
		mAdView.destroy();
		super.onDestroy();
	}

	/*-------------------------- Custom Function -----------------*/

	void addViewAds() {
		mAdView = (AdView) findViewById(R.id.adView);
		mAdView.loadAd(new AdRequest.Builder().build());
		mAdView.setAdListener(new AdListener() {

			@Override
			public void onAdOpened() {
				super.onAdOpened();
				isClickAds = true;

				ServerDelegate.updateTotalTimeClickAd(null, UtilsCommon
						.getStringSetting(getBaseContext(),
								ConstCommon.KEY_WIFI_STORE));
//				checkDisconnectWifi = false;
//				if(ConstCommon.isServiceRunning){
//					if(ConstCommon.totalSecondService == 0)
//						ConstCommon.totalSecondService = (ConstCommon.minuterFirst*60 - (ConstCommon.minuterService*60+ConstCommon.secondService));
//					else
//						ConstCommon.totalSecondService = (ConstCommon.minuterWait*60 - (ConstCommon.minuterService*60+ConstCommon.secondService));
//					ConstCommon.minuterService = ConstCommon.minuterWait;
//					ConstCommon.secondService = 0;
//					ServerDelegate.updateTotalTimeShowAd(null, UtilsCommon
//							.getStringSetting(getBaseContext(),
//									ConstCommon.KEY_WIFI_STORE), String
//							.valueOf(ConstCommon.totalSecondService));
//				}
			}

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
			}

		});
	}

	void initDB() {
		mContext = this;
		mEntityWifi = new EntityWifi(mContext);
		listWifi = new ArrayList<ObjectWifi>();
		listWifiOnServer = new ArrayList<ObjectWifi>();
		listWifiSave = new ArrayList<ObjectWifi>();
		listWifiSave = new ArrayList<ObjectWifi>();
		checkDisconnectWifi = true;
		getCurrentLocation(mContext);
	}

	void initView() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(1);

		progressBarLoading = (ProgressBar) findViewById(R.id.progressBarLoading);
		progressBarLoading.setVisibility(View.VISIBLE);

		listView = (ListView) findViewById(R.id.listView);
		listView.setVisibility(View.INVISIBLE);

		setViewWifiSave();
		findViewById(R.id.free_wifi_go).setOnClickListener(this);

		mTextDown = (TextView) findViewById(R.id.chrome_text_time_down);
	}

	void setViewWifiSave() {
		listViewSave = (ListView) findViewById(R.id.listViewWifiSave);
		listWifiSave = mEntityWifi.getListWifiSaveAll();
		listWifiSave = UtilsCommon.getListWifiSave(mContext, listWifiSave);
		adapterWifiSave = new AdapterWifiSave(mContext, listWifiSave);
		listViewSave.setAdapter(adapterWifiSave);
	}

	void setView() {

		listView.setVisibility(View.VISIBLE);
		progressBarLoading.setVisibility(View.INVISIBLE);

		listWifi = UtilsCommon.getListWifiObject(mContext, listWifiOnServer);
		adapter = new AdapterWifi(this, listWifi);
		listView.setAdapter(adapter);
	}

	void activityFinish() {
		finish();
		overridePendingTransition(
				R.drawable.activity_transaction_trans_right_in,
				R.drawable.activity_transaction_trans_right_out);
	}

	Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			listWifiOnServer.clear();
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					JSONArray data = new JSONArray();
					data = dataJSONObject.getJSONArray("data");
					if (data != null && data.length() > 0) {
						JSONObject wifiJSONObject = null;
						for (int i = 0; i < data.length(); i++) {
							wifiJSONObject = new JSONObject();
							wifiJSONObject = data.getJSONObject(i);

							mObjectWifi = new ObjectWifi();
							mObjectWifi.setWifiBSSID(wifiJSONObject
									.getString("BSSID"));
							mObjectWifi.setWifiSSID(wifiJSONObject
									.getString("SSID"));
							mObjectWifi.setWifiPassword(wifiJSONObject
									.getString("passkey"));
							mObjectWifi.setLat(wifiJSONObject
									.getString("lattitue"));
							mObjectWifi.setLng(wifiJSONObject
									.getString("longitue"));
							listWifiOnServer.add(mObjectWifi);
						}
						wifiJSONObject = null;
						// vf.setDisplayedChild(1);
					} else {
						// vf.setDisplayedChild(2);
						// Intent intent = new Intent(mContext,
						// ChromeBrowserActivity.class);
						// intent.putExtra(ConstCommon.KEY_LINK_POLICY,
						// getString(R.string.link_policy));
						// ((Activity) mContext).startActivity(intent);
						// overridePendingTransition(
						// R.drawable.activity_transaction_trans_left_in,
						// R.drawable.activity_transaction_trans_left_out);
					}
				} catch (Exception e) {
					// vf.setDisplayedChild(2);
				}
			} else {
				// vf.setDisplayedChild(2);
			}
			setView();
		}
	};

	// lay vi tri hien tai
	private void getCurrentLocation(final Context context) {
		threadGetCurrentLocation.start();
	}

	// Luong
	Thread threadGetCurrentLocation = new Thread(new Runnable() {

		@Override
		public void run() {
			Looper.prepare();
			long minTime = 500;// Khai bao thoi gian toi thieu de check lai
								// mylocation la 1/2s
			float minDistance = 0;// khai bao khoang cach thay doi toi thieu la
									// 50 m de check lai mylocation
			// load class lay vi tri hien tai
			locManager = (LocationManager) mContext
					.getSystemService(Context.LOCATION_SERVICE);
			// thuc hien check gps va lay vi tri hien tai
			locListener = new MyLocationListener();
			gps_enabled = locManager
					.isProviderEnabled(LocationManager.GPS_PROVIDER);
			network_enabled = locManager
					.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
			if (network_enabled) {
				locManager.requestLocationUpdates(
						LocationManager.NETWORK_PROVIDER, minTime, minDistance,
						locListener);
			} else if (gps_enabled) {
				locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
						minTime, minDistance, locListener);
			}

			// thuc hien lap nhieu lan
			Looper.loop();
		}
	});
	
	
	class MyLocationListener implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			if (location != null) {
				currentLocation = location;
			}
		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}
	}
}
